package com.zt.student.service.impl;

import cn.hutool.log.Log;
import cn.hutool.log.LogFactory;
import com.zt.common.Do.OriginStudentDO;
import com.zt.common.common.ApiException;
import com.zt.common.common.CodeMsg;
import com.zt.common.pojo.origin.OriginStudent;
import com.zt.common.utils.JwtUtil;
import com.zt.student.dao.OriginStudentDao;
import com.zt.student.service.OriginStudentService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;

/**
 * description:
 * author:zt
 * date:2022-01-04
 */
@Service
@Transactional
public class OriginStudentServiceImpl implements OriginStudentService {
    private static final Log log = LogFactory.get();

    @Autowired
    private OriginStudentDao originStudentDao;

    @Override
    public OriginStudent getOriginStuById(String studentId) {
        return originStudentDao.getOriginStuById(studentId);
    }

    @Override
    public void updatePwd(String oldPwd, String newPwd, HttpServletRequest request) {
        String studentId = JwtUtil.decodedGetID(request.getHeader("authorization"));
        Subject subject = SecurityUtils.getSubject();
        UsernamePasswordToken token = new UsernamePasswordToken(studentId, oldPwd);

        //交给shiro校验原始密码是否正确
        try {
            log.info("修改密码前 校验 " + studentId + " 的原始密码");
            subject.login(token);
        }catch (UnknownAccountException ue){
            throw new ApiException(CodeMsg.USER_NOT_FOUND);
        }catch (IncorrectCredentialsException ie){
            throw new ApiException(CodeMsg.WRONG_PASSWORD);
        }

        OriginStudent student = originStudentDao.getOriginStuById(studentId);
        //生成存放在数据库的 加密后的新密码
        String pwd = new Md5Hash(newPwd, student.getSalt(), 1024).toHex();
        student.setPassword(pwd);
        originStudentDao.update(student);
    }

    /**
     * @param request 获取学生id
     * @return 返回学生学籍信息
     */
    @Override
    public OriginStudentDO getInfoById(HttpServletRequest request) {
        String studentId = JwtUtil.decodedGetID(request.getHeader("authorization"));
        return originStudentDao.getInfoById(studentId);
    }
}
